package com.gem.taskplan.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.gem.taskplan.adapter.MemberListAdapter;
import com.gem.taskplan.adapter.WorkNewsAdapter;
import com.gem.taskplan.javaBean.WorkNewsBean;
import com.gem.taskplan.service.CheckedNetWork;
import com.gem.taskplan.service.DialogTool;
import com.gem.taskplan.util.HttpUtil;
import com.gem.taskplan.util.PropertiesUtil;
import com.gem.taskplan.util.SysApplication;
import com.gem.taskplan.util.Tools;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.format.Time;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class WorkNewsActivity extends Activity{

	private static String url = "/NewServlet";		//查询动态的列表
	private static String url1 = "/SetServlet";		//查询成员列表的路径
	private static String url2 = "/ProjectServlet";	//查询项目列表的路径
	private SharedPreferences sharedPreferences;	//用来过去本地保存的用户名	
	private static String curUser ;					//当前登陆用户
	//成员列表
	private ListView userListView = null;			//测试，按成员列表过滤弹出的dialog显示的listview
	private EditText userEditText = null;			//保存选择的成员
	//项目列表
	private ListView objListView = null;			//测试，按项目列表过滤弹出的dialog显示的listview
	private EditText objEditText = null;			//保存选择的项目
	//工作动态显示的listview
	private ListView workNewsListView = null;		//工作动态中的listview
	private SwipeRefreshLayout refreashNews;		//下拉刷新
	//	private SimpleAdapter simpleAdapter;
	private static WorkNewsAdapter workNewsAdapter;
	private ImageView downPupWindow = null;			//弹出窗的方向箭头图片
	private PopupWindow popupWindow  = null;		//弹出窗
	private ListView listViewNews ;        			//popupwindow弹出窗中显示的listview
	private RelativeLayout workNews = null;			//动态的title，点击出现弹出框	
	private View popView = null;					//用来获取popupwindow所在的布局文件（XML）
	private List<Map<String, String>> list ;
	private static List<WorkNewsBean> list1 = new ArrayList<WorkNewsBean>();
	private Map<String, String> map = null;
	private MemberListAdapter memberListAdapter = null;
	private String[] workNewsArray = new String[]{"按时间过滤","按操作过滤","按成员过滤","按项目过滤"};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_work_news);
		
		/***********退出程序************/
		SysApplication.getInstance().addActivity(this);
		
		
		/************获得访问服务器的地址***************/
		url = "/NewServlet";
		url1 = "/SetServlet";
		url2 = "/ProjectServlet";
		url = PropertiesUtil.getServerURL(this)+url;
		url1 = PropertiesUtil.getServerURL(this)+url1;
		url2 = PropertiesUtil.getServerURL(this)+url2;
		System.out.println("工作台访问服务器地址：--------------"+url);

		/*****************************************/
		downPupWindow = (ImageView) findViewById(R.id.downPupWindow);
		workNewsListView = (ListView) findViewById(R.id.workNewsListView);
		refreashNews = (SwipeRefreshLayout) findViewById(R.id.refreshNews);
		sharedPreferences = WorkNewsActivity.this.getSharedPreferences("taskPlanShare", Activity.MODE_PRIVATE);
		curUser = sharedPreferences.getString("lastUser", "");
		//工作动态数据的适配器
		workNewsAdapter = new WorkNewsAdapter(WorkNewsActivity.this, list1);
		workNewsListView.setAdapter(workNewsAdapter);
		//数据源
		initList();
		//工作动态数据刷新监听：
		refreashNews.setColorScheme(android.R.color.holo_red_light, android.R.color.holo_green_light,
				android.R.color.holo_blue_bright, android.R.color.holo_orange_light);//添加刷新颜色变化
		refreashNews.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh() {
				new Handler().postDelayed(new Runnable() {
					public void run() {
						refreashNews.setRefreshing(false);
						initList();
					}
				}, 500);
			}
		});


		workNews = (RelativeLayout) findViewById(R.id.title1);
		workNews.setOnClickListener(new WorkNewsOnClickListener());
	}
	/*********************************工作动态弹出listView窗口*************************************/
	private class WorkNewsOnClickListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			downPupWindow.setImageResource(R.drawable.listinfo_pupwindow);
			list = new ArrayList<Map<String,String>>();
			for(int i=0;i<workNewsArray.length;i++){
				Map<String, String> map = new HashMap<String, String>();
				map.put("item1", workNewsArray[i]);
				list.add(map);
			}
			SimpleAdapter simpleAdapter = new SimpleAdapter(WorkNewsActivity.this, list, R.layout.popupwindow_activity_list, new String[]{"item1"}, new int[]{R.id.choose});

			LayoutInflater inflater = LayoutInflater.from(WorkNewsActivity.this);

			popView = inflater.inflate(R.layout.popupwindow_activity, null);
			listViewNews = (ListView) popView.findViewById(R.id.listViewNews);
			listViewNews.setAdapter(simpleAdapter);

			popupWindow = new PopupWindow(popView, 200, 250,true);
			int xoff = popupWindow.getWidth() / 2 - workNews.getWidth() / 2;  
			// 将pixels转为dip  
			popupWindow.setFocusable(true);
			popupWindow.setOutsideTouchable(true);
			popupWindow.setBackgroundDrawable(new BitmapDrawable());
			popupWindow.showAsDropDown(workNews, -xoff, 0);
			listViewNews.setOnItemClickListener(new OnItemClickListenerImpl());
			popupWindow.setOnDismissListener(new OnDismissListener() {
				@Override
				public void onDismiss() {
					downPupWindow.setImageResource(R.drawable.down_popupwindow);
				}
			});
		}
	}
	/*********************************（过滤）工作动态的弹出窗口的listView的监听事件*************************************/
	private class OnItemClickListenerImpl implements OnItemClickListener{
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			LayoutInflater inflater = getLayoutInflater();
			System.out.println("事件监听");
			//获取过滤布局文件
			View vTime = inflater.inflate(R.layout.base_time_dialog, null);
			View vPoeration = inflater.inflate(R.layout.base_operation_dialog, null);
			View vUser = inflater.inflate( R.layout.base_user_dialog, null);
			View vObj = inflater.inflate(R.layout.base_object_dialog, null);
			//------------------------------
			Dialog dialog = null;
			DialogTool dialogTool = new DialogTool(WorkNewsActivity.this);
			TextView startTime = (TextView) vTime.findViewById(R.id.startTime);
			TextView endTime = (TextView) vTime.findViewById(R.id.endTime);
			RelativeLayout time1 = (RelativeLayout) vTime.findViewById(R.id.time1);
			RelativeLayout time2 = (RelativeLayout) vTime.findViewById(R.id.time2);

			dialogTool.getTimeDialog(startTime,time1,"time1");
			dialogTool.getTimeDialog(endTime, time2, "time2");

			userEditText = (EditText) vUser.findViewById(R.id.userEdit);
			objEditText = (EditText) vObj.findViewById(R.id.projectEdit);
			TextView text = (TextView) view.findViewById(R.id.choose);
			if (text.getText().toString().equals(workNewsArray[0])) {
				System.out.println("**************************");
				dialog = dialogTool.getDialog(vTime,"按时间过滤",popupWindow);
				WindowManager m = getWindowManager(); 
				Tools.dialogHightWidth(dialog, m);
//				dialog.getWindow().setLayout(550, 700);
//				Map<String, String> map1 = dialogTool.getHttpMap(vTime,"按时间过滤");
			}else if (text.getText().toString().equals(workNewsArray[1])) {
				System.out.println("---------按操作过滤------------");
				final Dialog dialogOperation = new AlertDialog.Builder(WorkNewsActivity.this)
				.setTitle("按操作过滤").setView(vPoeration).setNegativeButton("取消", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						
					}
				}).create();
				WindowManager m = getWindowManager(); 
				Tools.dialogHightWidth(dialogOperation, m);
//				dialogOperation.getWindow().setLayout(550, 700);
				final TextView addSearch = (TextView) vPoeration.findViewById(R.id.addSearch);
				final TextView updateSearch = (TextView) vPoeration.findViewById(R.id.updateSearch);
				final TextView commitSearch = (TextView) vPoeration.findViewById(R.id.commitSearch);
				final TextView deleteSearch = (TextView) vPoeration.findViewById(R.id.deleteSearch);
				map.put("curName", curUser);
				map.put("action", "baseOperation");
				addSearch.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						map.put("base_Search", addSearch.getText().toString());
						dialogOperation.cancel();
						popupWindow.dismiss();
						refreashList(map);
						return ;
					}
				});
				updateSearch.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						map.put("base_Search", updateSearch.getText().toString());
//						map.put("action", "baseOperation");
						dialogOperation.cancel();
						popupWindow.dismiss();
						refreashList(map);
						return;
					}
				});
				commitSearch.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						map.put("base_Search", commitSearch.getText().toString());
//						map.put("action", "baseOperation");
						dialogOperation.cancel();
						popupWindow.dismiss();
						refreashList(map);
						return;
					}
				});
				deleteSearch.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						map.put("base_Search", deleteSearch.getText().toString());
//						map.put("action", "baseOperation");
						dialogOperation.cancel();
						popupWindow.dismiss();
						refreashList(map);
						return;
					}
				});
			}else if (text.getText().toString().equals(workNewsArray[2])) {
				System.out.println("++++++++++++++++++++++++++");
				System.out.println("添加成员");
				List<Map<String, String>> listUser = new ArrayList<Map<String,String>>();
				memberListAdapter = new MemberListAdapter(listUser, WorkNewsActivity.this, R.layout.choose_member_list2);
				init(listUser);
				userListView = (ListView) vUser.findViewById(R.id.userList);
				userListView.setAdapter(memberListAdapter);
				userListView.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view, int position,
							long id) {
						TextView text = (TextView) view.findViewById(R.id.memberName);
						userEditText.setText(text.getText().toString());
					}
				});
				dialog = dialogTool.getDialog(vUser,"按成员过滤",popupWindow);
				WindowManager m = getWindowManager(); 
				Tools.dialogHightWidth(dialog, m);
//				dialog.show();
//				dialog.getWindow().setLayout(550, 700);
			}if (text.getText().toString().equals(workNewsArray[3])) {
				objListView = (ListView) vObj.findViewById(R.id.objList);
				list = new ArrayList<Map<String,String>>();
				SimpleAdapter simpleAdapter = new SimpleAdapter(WorkNewsActivity.this, 
						list, R.layout.obj_list, new String[]{"obj"}, new int[]{R.id.objList_tv});
				initProjectDialog(list, simpleAdapter);
				objListView.setAdapter(simpleAdapter);
				objListView.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view, int position,
							long id) {
						System.out.println("获取list中的值");
						TextView text = (TextView) view.findViewById(R.id.objList_tv);
						objEditText.setText(text.getText().toString());
					}
				});
				dialog = dialogTool.getDialog(vObj,"按项目过滤",popupWindow);
				WindowManager m = getWindowManager(); 
				Tools.dialogHightWidth(dialog, m);
//				dialog.show();
//				dialog.getWindow().setLayout(550, 700);
			}
		}

	}
	/*******************动态查询************************/
	private void initList(){
		//验证时否联网
		if(!CheckedNetWork.checkedConnection(this)){
			return;
		}
		map = new HashMap<String, String>();
		map.put("action", "newsQuery");
		map.put("user_name",curUser);
		System.out.println("workNews"+curUser);
		refreashList(map);
	}

	/***********************初始化数据****************************/
	public static void refreashList(Map<String, String> map){
		String result = null;
		try {
			result = HttpUtil.postRequest(url, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (result==null) {
			return;
		}
		System.out.println("result = "+result);
		String[] string = new String[]{"new_time","new_member","new_task","new_operation","new_project","user_picture"};
		String[] state = {"待做","在做","完成"};
		try {
			JSONObject object = new JSONObject(result);
			JSONArray array = object.getJSONArray("newsListJson");
			System.out.println("*********"+array.length());
			list1.clear();
			WorkNewsBean[] workNewsBean = new WorkNewsBean[array.length()];
			for (int j = 0; j < array.length(); j++) {
				JSONObject object3 = array.getJSONObject(j);
				JSONArray array2 = object3.getJSONArray("newsListJson"+j);
				System.out.println("*********"+array2.length());
				String date = array2.getJSONObject(0).getString(string[0]);
				String name = array2.getJSONObject(1).getString(string[1]);
				String task = array2.getJSONObject(2).getString(string[2]);
				String operation = array2.getJSONObject(3).getString(string[3]);
				String project = array2.getJSONObject(4).getString(string[4]);
				String url = array2.getJSONObject(5).getString(string[5]);
				workNewsBean[j] = new WorkNewsBean();
				if (name.equals(curUser)) {
					workNewsBean[j].setComMM(false);
				}else {
					workNewsBean[j].setComMM(true);
				}
				workNewsBean[j].setDate(date);
				workNewsBean[j].setName(name);
				if (task.equals("")) {
					workNewsBean[j].setText(operation+":"+project);
					System.out.println(operation+":"+project);
				}else {
					
//					String operString  = operation.replaceAll("\\D+", "").toString();
					boolean flag = operation.contains("-");
					if (flag) {
					    String[] time = operation.split("\\,");
//					    System.out.println("把任务“ "+task+" ”的截止时间由原时间“ "+time[0]+" ”"+"修改至“ "+time[1]+" ”");
//					    System.out.println("把任务“ "+task+" ”的截止时间由原时间“ "+time[0]+" ”"+"修改至“ "+time[1]+" ”");
//					    System.out.println("把任务“ "+task+" ”的截止时间由原时间“ "+time[0]+" ”"+"修改至“ "+time[1]+" ”");
						workNewsBean[j].setText("把任务“ "+task+" ”的截止时间\n由原来的“ "+time[0]+" ”"+"\n修改至“ "+time[1]+" ”");
						
					}else {
						
					String operString  = operation.replaceAll("\\D+", "").toString();
						if (operString.length()==0) {
							workNewsBean[j].setText(operation+"“ "+task+" ”");
						}else {
							int i = Integer.parseInt(operString);
							workNewsBean[j].setText("移动任务“ "+task+" ”的状态至“ "+state[i-1]+" ”");
							System.out.println(operation+":"+task);
						}
					}
				}
				if (url.length() == 0) {
					workNewsBean[j].setHead("");
				}else {
					workNewsBean[j].setHead(url);
				}
				list1.add(workNewsBean[j]);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		workNewsAdapter.notifyDataSetChanged();
		
	}
	/***********************查询成员****************************/
	public void init(List<Map<String, String>> list1){
		Map<String, String> map1 = new HashMap<String, String>();
		map1.put("user_name", curUser);
		map1.put("action", "queryUser");
		String result = null;
		try {
			result = HttpUtil.postRequest(url1, map1);
		} catch (Exception e) {
			e.printStackTrace();
		}
//		System.out.println("工作动态 result = "+result);
		String[] string = new String[]{"user_picture","user_name","user_sex","user_email"};
		try {
			JSONObject object = new JSONObject(result);
			JSONArray array = object.getJSONArray("userListJson");
			list1.clear();
			for (int j = 0; j < array.length(); j++) {
				JSONObject object3 = array.getJSONObject(j);
				JSONArray array2 = object3.getJSONArray("userListJson"+j);
				String url = array2.getJSONObject(0).getString(string[0]);
				String name = array2.getJSONObject(1).getString(string[1]);
				Map<String , String> map = new HashMap<String, String>();
				if (url.length() == 0) {
					map.put("url","");
				}else {
					map.put("url",url);
				}
				map.put("name", name);
				map.put("checked", "0");
				list1.add(map);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		//刷新数据
		memberListAdapter.notifyDataSetChanged();
	}
	private void initProjectDialog(final List<Map<String, String>> list , final SimpleAdapter simpleAdapter){
		System.out.println(curUser);
		AjaxParams params = new AjaxParams();
		params.put("user_name", curUser);
		params.put("action", "query");
		FinalHttp fh = new FinalHttp();
		fh.post(url2, params, new AjaxCallBack<String>() {
			@Override
			public void onFailure(Throwable t, String strMsg) {
				super.onFailure(t, strMsg);
//				Toast.makeText(WorkNewsActivity.this, "添加项目失败", Toast.LENGTH_LONG).show();
			}
			@Override
			public void onSuccess(String t) {
				System.out.println("t = "+t);
				String[] string = new String[]{"project_name","project_outOfDate","project_creator","project_team"};
				try {
					JSONObject object = new JSONObject(t);
					JSONArray array = object.getJSONArray("projectListJson");
					for (int j = 0; j < array.length(); j++) {
						JSONObject object3 = array.getJSONObject(j);
						JSONArray array2 = object3.getJSONArray("projectListJson"+j);
						Map<String , String> map = new HashMap<String, String>();
						map.put("obj", array2.getJSONObject(0).getString(string[0]));
						list.add(map);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				//刷新数据
				simpleAdapter.notifyDataSetChanged();
				super.onSuccess(t);
			}
		});
	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
			DialogTool.existDialog(this);
		}
		return super.onKeyDown(keyCode, event);
	}

}
